#include <cstring>
#include <R.h>
#include <Rmath.h>
#include <Rinternals.h>



#define USE_RINTERNALS


extern "C" {

void cashNumberToText(double *number,int *n, char **out){
	double numberLeft,numberRight,numberFull,numberOrg,numberSign;
	char currentText[50],currentRound[3],finalText[50],pointText[2];
	int lengthNumberLeft,q,signShift;
	pointText[0] = '.';
	pointText[1] = '\0';
	for(int i=0;i<*n;i++){
		numberOrg = number[i];
		numberSign = Rf_sign(numberOrg);
		numberFull = Rf_fround(numberOrg * numberSign,2);
		numberLeft = floor(numberFull);
		numberRight = numberFull - numberLeft;
		sprintf(currentText,"%.0f",numberLeft);
		sprintf(currentRound,"%02i",(int)Rf_fround((numberRight*100),0));
		lengthNumberLeft = (int)strlen(currentText);
		q = 0;
		
		signShift = 0;
		if(numberSign<0){
			finalText[0] = '-';
			signShift = 1;
		}
		
		for(int k=0;k<lengthNumberLeft;k++){
			finalText[k + q + signShift] = currentText[k];
			if((double)(lengthNumberLeft-1-k)/ 3 == floor((double)(lengthNumberLeft-1-k)/ 3)){
				if((lengthNumberLeft-1-k)>0){
					q++;
					finalText[k + q + signShift] = '\'';
				}

			}
		}
		finalText[lengthNumberLeft + q + signShift] = '\0';

		strcat(finalText,pointText);
		strcat(finalText,currentRound);
		strcpy(out[i],finalText);
	}
}
}
